<?php
/**
 * 用户足迹模型
 */

namespace app\api\model;


use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class UserTrack extends BaseModel {

    /**
     * 添加历史记录
     * @param $user_id
     * @param $house_id
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public static function add($user_id, $house_id) {
        $has = db('user_track')->where('user_id', $user_id)->find();
        if (empty($has)) {
            $insert = [
                'user_id' => $user_id,
                'house_id' => $house_id,
            ];
            db('user_track')->insert($insert);
        } else {
            $house_ids = explode(',', $has['house_id']);
            if (!in_array($house_id, $house_ids)) {
                if (count($house_ids) >= 10) {
                    array_shift($house_ids);
                    $house_ids[] = $house_id;
                    $new = join(',', $house_ids);
                    db('user_track')->where('user_id', $user_id)->update(['house_id' => $new]);
                } else {
                    $house_ids[] = $house_id;
                    $new = join(',', $house_ids);
                    db('user_track')->where('user_id', $user_id)->update(['house_id' => $new]);
                }
            }
        }
    }

    /**
     * 用户足迹房源
     * @param $params
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function show($params) {
        $house_id = db('user_track')->where('user_id', $params['user_id'])->value('house_id');
        if (empty($house_id)) {
            return [];
        } else {
            $house_ids = explode(',', $house_id);
            $House = new House();
            $column = array_merge($House->houseFields, $House->villageFields, $House->typeFields, $House->auctionFields,$House->businessFields,$House->reginFields);
            krsort($house_ids);
            $house_ids = array_merge($house_ids);
            $map[] = ['h.id', 'in', $house_ids];
            $map[] = ['h.is_shelf', '=', 1];
            $house_id_str = join(',', $house_ids);
            $re = $House->house_list($map, '', $column, 1, 10, [], $house_id_str)[0];
            $re = House::house_list_style($re);
            return $re;
        }
    }

}
